// import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
// import 'package:flutter_dotenv/flutter_dotenv.dart';

String encryptWithRSAPublicKey(String publicKey, String plainText) {
  try {
    // Clean and format the public key
    String cleanedPublicKey = _formatPublicKey(publicKey);

    final parser = RSAKeyParser();
    final rsaPublicKey = parser.parse(cleanedPublicKey) as RSAPublicKey;

    // Only use public key for encryption (no private key needed)
    final encrypter = Encrypter(RSA(publicKey: rsaPublicKey));
    final encrypted = encrypter.encrypt(plainText);

    print('RSA加密成功: ${encrypted.base64}');
    return encrypted.base64;
  } catch (e) {
    print('RSA加密失败: $e');
    print('公钥内容: $publicKey');
    print('明文内容: $plainText');
    throw Exception('RSA加密失败: $e');
  }
}

String _formatPublicKey(String publicKey) {
  // Remove all whitespace and newlines
  String cleaned = publicKey.replaceAll(RegExp(r'\s+'), '');

  // Remove existing headers if present
  cleaned = cleaned
      .replaceAll('-----BEGINPUBLICKEY-----', '')
      .replaceAll('-----ENDPUBLICKEY-----', '')
      .replaceAll('-----BEGINRSAPUBLICKEY-----', '')
      .replaceAll('-----ENDRSAPUBLICKEY-----', '');

  // Add proper PEM headers with correct formatting
  return '-----BEGIN PUBLIC KEY-----\n$cleaned\n-----END PUBLIC KEY-----';
}
